package test;
//RealTimeChart .java

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import utils.ExcelManager;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;

public class RealTimeChart extends ChartPanel implements Runnable {
    private static TimeSeries timeSeries;
    private static String[][] sys_info;
    private long value = 0;
    private int count = 0;

    public RealTimeChart(String chartContent, String title, String yaxisName) throws IOException, InvalidFormatException {
        super(createChart(chartContent, title, yaxisName));

    }

    private static JFreeChart createChart(String chartContent, String title, String yaxisName) throws IOException, InvalidFormatException {

        sys_info = ExcelManager.readExcelFile("F:\\common_soft\\phpstudy\\WWW\\jquery\\hello.xlsx");

        //创建时序图对象
        timeSeries = new TimeSeries(chartContent, Millisecond.class);
        TimeSeriesCollection timeseriescollection = new TimeSeriesCollection(timeSeries);
        JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(title, "时间(秒)", yaxisName, timeseriescollection, true, true, false);
        XYPlot xyplot = jfreechart.getXYPlot();
        //纵坐标设定
        ValueAxis valueaxis = xyplot.getDomainAxis();
        //自动设置数据轴数据范围
        valueaxis.setAutoRange(true);
        //数据轴固定数据范围 30s
        valueaxis.setFixedAutoRange(30000D);

        valueaxis = xyplot.getRangeAxis();
        //valueaxis.setRange(0.0D,200D);

        return jfreechart;
    }

    public void run() {
        while (true) {
            try {
                timeSeries.add(new Millisecond(), Float.parseFloat(sys_info[count][0]));
                count += 1;
                Thread.sleep(300);
                System.out.println(count);
            } catch (InterruptedException | ArrayIndexOutOfBoundsException e) {
                count = 0;
            }
        }
    }


}
